package com.wtwd.campus.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespCodeEntity;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.dao.DeviceInfoMapper;
import com.wtwd.campus.dao.SchoolMapper;
import com.wtwd.campus.dao.StudentMapper;
import com.wtwd.campus.dao.WXUserStudentPermissionMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.jdzc.common.Constant;
import com.wtwd.campus.service.ClassesService;
import com.wtwd.campus.service.StudentService;
import com.wtwd.campus.utils.ExcelUtils;
import com.wtwd.campus.utils.MyExcelUtils;
import com.wtwd.campus.wx.entity.WxUserStudentPermission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mjy
 * @date 2021/06/11
 * @description
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private WXUserStudentPermissionMapper wxUserStudentPermissionMapper;

    @Override
    public Integer getStudentCountByOrgCode(String orgCode) {
        //根据组织code查询出学校id
        List<Integer> schoolIdList = schoolMapper.getSchoolIdListByOrgCode(orgCode);
        //查询学校下面所有学生数量
        Integer studentNum = 0;
        if (schoolIdList != null && schoolIdList.size() > 0) {
            studentNum = studentMapper.getStudentCountBySchoolIdList(schoolIdList);
        }
        return studentNum;
    }


    @Override
    public RespCodeEntity checkStudent(VoStudent voStudent) {
        Student student = studentMapper.getStudentByStudentNoAndSchoolId(voStudent.getSchoolId(), voStudent.getStuNo());
        if (student != null) {//鉴别学号是否重复
            return new RespCodeEntity(RespCode.EXIST_STUDENTNO);
        }
/*        if (voStudent.getStuPhone() != null && student.getStuPhone() != "") {
            Student student2 = studentMapper.getStudentByStuPhone(voStudent.getStuPhone());
            if (student2 != null) {//鉴别是否已经存在该手机号的学生
                return new RespCodeEntity(RespCode.STUDENT_EXIST);
            }
        }*/
        return new RespCodeEntity(RespCode.SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addStudent(VoStudent voStudent) {
        Integer rest = studentMapper.addStudent(voStudent);
        if (voStudent.getDeviceId() != null) {
            //绑定设备
            School school = schoolMapper.getSchoolInfoBySchoolId(voStudent.getSchoolId());
            //绑定设备的同时,同步设备到该学生的学校
            deviceInfoMapper.bindDeviceAndSynchronizationOrg(voStudent.getStuId(), voStudent.getDeviceId(), school.getOrgCode(), school.getSchoolName());
        }
        return rest;
    }

    @Override
    public IPage<Map<String, Object>> getStudentListByCondition(Map searchMap, Page<Student> page) {
        return studentMapper.getStudentListByCondition(searchMap, page);
    }

    @Override
    public RespCodeEntity checkUpdateStudent(VoStudent voStudent) {
        Student student = studentMapper.getStudentByStudentNoAndSchoolId(voStudent.getSchoolId(), voStudent.getStuNo());
        if (student != null) {//校验修改后的学号在该学校中是否已经存在
            if (!voStudent.getSchoolId().equals(student.getStudentId())) {
                new RespCodeEntity(RespCode.EXIST_STUDENTNO);
            }
        }
/*        if (voStudent.getStuPhone() != null && student.getStuPhone() != "") {
            Student student1 = studentMapper.getStudentByStuPhone(voStudent.getStuPhone());
            if (student1 != null) {
                if (!voStudent.getStuId().equals(student1.getStudentId())) {
                    new RespCodeEntity(RespCode.STUDENT_EXIST);
                }
            }
        }*/
        return new RespCodeEntity(RespCode.SUCCESS);
    }

    @Override
    public Integer updateStudent(VoStudent voStudent) {
        return studentMapper.updateStudent(voStudent);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteStudentByStudentId(Integer studentId) {
        //解绑学生绑定的设备
        deviceInfoMapper.noBind(studentId);
        //解绑该学生在微信端绑定的所有家长
        wxUserStudentPermissionMapper.unbindStudentAllParents(studentId);
        //删除该学生
        Integer rest = studentMapper.deleteStudent(studentId);
        return rest;
    }

    @Override
    public List<Map<String, Object>> getWxUserByStudentId(Integer studentId) {
        return studentMapper.getWxUserByStudentId(studentId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespEntity importStudent(MultipartFile file, SysUser sysUser, HttpServletResponse response) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelImportStudentInfo> failMessages = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //记录需要添加的学生的学生信息
        List<Student> students = new ArrayList<>();
        //记录需要绑定的设备信息
        List<DeviceInfo> deviceInfos = new ArrayList<>();
        //标记设备与学生之间的绑定关系
        List<Map<String, Object>> flag = new ArrayList<>();
        //读取文件信息
        List<ExcelImportStudentInfo> excelImportStudents = null;
        try {
            excelImportStudents = MyExcelUtils.importExcel(file, 6, 1, ExcelImportStudentInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (excelImportStudents != null && excelImportStudents.size() > 0) {
            aa:
            for (ExcelImportStudentInfo excelImportStudent : excelImportStudents) {
                //检测必传参数是否为空
                if (StringUtils.isBlank(excelImportStudent.getStuName()) || StringUtils.isBlank(excelImportStudent.getStuNo())
                        || StringUtils.isBlank(excelImportStudent.getGradeName()) || StringUtils.isBlank(excelImportStudent.getClassesName())
                        || StringUtils.isBlank(excelImportStudent.getSchoolName())
                ) {
                    ExcelImportStudentInfo failMessage = new ExcelImportStudentInfo();
                    failMessage.setStuName(excelImportStudent.getStuName());
                    failMessage.setStuNo(excelImportStudent.getStuNo());
                    failMessage.setGradeName(excelImportStudent.getGradeName());
                    failMessage.setClassesName(excelImportStudent.getClassesName());
                    failMessage.setSchoolName(excelImportStudent.getSchoolName());
                    failMessage.setImei(excelImportStudent.getImei());
                    failMessage.setStuPhone(excelImportStudent.getStuPhone());
                    failMessage.setParentsName(excelImportStudent.getParentsName());
                    failMessage.setParentsPhone(excelImportStudent.getParentsPhone());
                    failMessage.setMessage("必填项为空");
                    failMessages.add(failMessage);
                    continue;
                }
                //鉴别在自己的权限类是否可以在该学校的该班级下添加学生(和是否存该学校，年级和班级一起鉴)
                //条件，组织code,学校名称，年级名称，班级名称
                Classes classes = classesService.getClassesInfoByCondition(sysUser.getOrgCode(), excelImportStudent);
                if (classes == null) {//记录失败文件，以及失败原因
                    ExcelImportStudentInfo failMessage = new ExcelImportStudentInfo();
                    failMessage.setStuName(excelImportStudent.getStuName());
                    failMessage.setStuNo(excelImportStudent.getStuNo());
                    failMessage.setGradeName(excelImportStudent.getGradeName());
                    failMessage.setClassesName(excelImportStudent.getClassesName());
                    failMessage.setSchoolName(excelImportStudent.getSchoolName());
                    failMessage.setImei(excelImportStudent.getImei());
                    failMessage.setStuPhone(excelImportStudent.getStuPhone());
                    failMessage.setParentsName(excelImportStudent.getParentsName());
                    failMessage.setParentsPhone(excelImportStudent.getParentsPhone());
                    failMessage.setMessage("学校名称，年级名称，班级名称输入有误(或者无权处理)");
                    failMessages.add(failMessage);
                    continue;
                }
                //鉴别添加的学生信息是否有误
                //鉴别添加学生的学号是否在该学校已经存在
                Student student = studentMapper.getStudentByStudentNoAndSchoolName(excelImportStudent.getSchoolName(), excelImportStudent.getStuNo());
                if (student != null) {
                    ExcelImportStudentInfo failMessage = new ExcelImportStudentInfo();
                    failMessage.setStuName(excelImportStudent.getStuName());
                    failMessage.setStuNo(excelImportStudent.getStuNo());
                    failMessage.setGradeName(excelImportStudent.getGradeName());
                    failMessage.setClassesName(excelImportStudent.getClassesName());
                    failMessage.setSchoolName(excelImportStudent.getSchoolName());
                    failMessage.setImei(excelImportStudent.getImei());
                    failMessage.setStuPhone(excelImportStudent.getStuPhone());
                    failMessage.setParentsName(excelImportStudent.getParentsName());
                    failMessage.setParentsPhone(excelImportStudent.getParentsPhone());
                    failMessage.setMessage("学号已存在");
                    failMessages.add(failMessage);
                    continue;
                }
                //鉴别此次添加的学生学号在excel中是否已经存在
                if (students != null && students.size() > 0) {
                    for (Student student1 : students) {
                        if (student1.getStudentNo().equals(excelImportStudent.getStuNo())) {
                            ExcelImportStudentInfo failMessage = new ExcelImportStudentInfo();
                            failMessage.setStuName(excelImportStudent.getStuName());
                            failMessage.setStuNo(excelImportStudent.getStuNo());
                            failMessage.setGradeName(excelImportStudent.getGradeName());
                            failMessage.setClassesName(excelImportStudent.getClassesName());
                            failMessage.setSchoolName(excelImportStudent.getSchoolName());
                            failMessage.setImei(excelImportStudent.getImei());
                            failMessage.setStuPhone(excelImportStudent.getStuPhone());
                            failMessage.setParentsName(excelImportStudent.getParentsName());
                            failMessage.setParentsPhone(excelImportStudent.getParentsPhone());
                            failMessage.setMessage("重复导入的学生学号");
                            failMessages.add(failMessage);
                            continue aa;
                        }
                    }
                }
                //鉴别绑定的imei号是否已经绑定（获取说是否存在该设备的imei号，是否有权操作该imei号）
                //1.条件，imei,orgCode(最多只有一条)
                if (!StringUtils.isBlank(excelImportStudent.getImei())) {//如果添加学生绑定了设备
                    DeviceInfo deviceInfo = new DeviceInfo();
                    deviceInfo.setImei(excelImportStudent.getImei().trim());
                    deviceInfo.setOrgCode(sysUser.getOrgCode());
                    DeviceInfo device = deviceInfoMapper.getDeviceByCondition(deviceInfo);
                    if (device == null) {
                        ExcelImportStudentInfo failMessage = new ExcelImportStudentInfo();
                        failMessage.setStuName(excelImportStudent.getStuName());
                        failMessage.setStuNo(excelImportStudent.getStuNo());
                        failMessage.setGradeName(excelImportStudent.getGradeName());
                        failMessage.setClassesName(excelImportStudent.getClassesName());
                        failMessage.setSchoolName(excelImportStudent.getSchoolName());
                        failMessage.setImei(excelImportStudent.getImei());
                        failMessage.setStuPhone(excelImportStudent.getStuPhone());
                        failMessage.setParentsName(excelImportStudent.getParentsName());
                        failMessage.setParentsPhone(excelImportStudent.getParentsPhone());
                        failMessage.setMessage("不存在该设备的imei号，或者说无权处理");
                        failMessages.add(failMessage);
                        continue;
                    }
                    if (device.getStudentId() != null) {
                        ExcelImportStudentInfo failMessage = new ExcelImportStudentInfo();
                        failMessage.setStuName(excelImportStudent.getStuName());
                        failMessage.setStuNo(excelImportStudent.getStuNo());
                        failMessage.setGradeName(excelImportStudent.getGradeName());
                        failMessage.setClassesName(excelImportStudent.getClassesName());
                        failMessage.setSchoolName(excelImportStudent.getSchoolName());
                        failMessage.setImei(excelImportStudent.getImei());
                        failMessage.setStuPhone(excelImportStudent.getStuPhone());
                        failMessage.setParentsName(excelImportStudent.getParentsName());
                        failMessage.setParentsPhone(excelImportStudent.getParentsPhone());
                        failMessage.setMessage("该设备已经绑定学生");
                        failMessages.add(failMessage);
                        continue;
                    }
                    //记录导入学生时，绑定的设备
                    //标记绑定关系
                    //根据学校名称找到该学校信息，并将设备同步到该学校
                    School school = schoolMapper.getSchoolInfoBySchoolName(excelImportStudent.getSchoolName(),sysUser.getOrgCode());
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("deviceId", device.getDeviceId());
                    map.put("stuNo", excelImportStudent.getStuNo());
                    map.put("orgName", school.getSchoolName());
                    map.put("orgCode", school.getOrgCode());
                    flag.add(map);
                }
                //以上鉴别全部成功，进入信息记录阶段
                Student newStudent = new Student();
                newStudent.setStudentNo(excelImportStudent.getStuNo());
                newStudent.setStudentName(excelImportStudent.getStuName());
                newStudent.setStudentPhone(excelImportStudent.getStuPhone());
                newStudent.setClassesId(classes.getClassesId());
                newStudent.setBindingWechat(0);
                newStudent.setParentPhone(excelImportStudent.getParentsPhone());
                newStudent.setParentName(excelImportStudent.getParentsName());
                students.add(newStudent);
            }
        }
        if (students != null && students.size() > 0) {
            //执行批量添加学生操作(添加时返回主键)
            studentMapper.batchAddStudent(students);
            //构建批量绑定设备数据
            for (Student student : students) {
                for (Map<String, Object> map : flag) {
                    if (student.getStudentNo().equals(map.get("stuNo"))) {//学号相同认为是同一组数据
                        DeviceInfo device = new DeviceInfo();
                        device.setStudentId(student.getStudentId());
                        device.setDeviceId((Integer) map.get("deviceId"));
                        device.setOrgName((String)map.get("orgName"));
                        device.setOrgCode((String)map.get("orgCode"));
                        deviceInfos.add(device);
                    }
                }
            }
            if(deviceInfos!=null&&deviceInfos.size()>0){
                //批量绑定设备
                deviceInfoMapper.batchBindDevice(deviceInfos);
            }
        }
        //导出失败文件信息
        Integer failNum = 0;
        if (failMessages != null && failMessages.size() > 0) {
            failNum = failMessages.size();
            path = MyExcelUtils.exportExcel(failMessages, "学生信息", "学生信息", ExcelImportStudentInfo.class, "学生文件导入失败信息.xls", response);
        }
        //构建返回值集合
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("path", path);
        restMap.put("successNum", students != null ? students.size() : 0);
        restMap.put("failNum", failNum);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    @Override
    public Integer updateStudentWxUserBindStatus(Integer bindingWechat, Integer studentId) {
        return studentMapper.updateStudentWxUserBindStatus(bindingWechat, studentId);
    }

    @Override
    public List<Map<String,Object>> getSchoolOrgCodeListByStuIdList(List<Integer> stuIdList) {
        return studentMapper.getSchoolOrgCodeListByStuIdList(stuIdList);
    }

    @Override
    public Map<String, Object> getSchoolIdAndClassIdByStuId(Integer stuId) {
        return studentMapper.getSchoolIdAndClassIdByStuId(stuId);
    }

    @Override
    public Map<String, Object> getStuBindingMessByStuId(Integer stuId) {
        return studentMapper.getStuBindingMessByStuId(stuId);
    }

    @Override
    public Map<String, Object> getStuMessByStuId(Integer stuId) {
        return studentMapper.getStuMessByStuId(stuId);
    }

    @Override
    public int getStudentNumberByClassId(Integer classId) {
        return studentMapper.getStudentNumberByClassId(classId);
    }

    @Override
    public List<Map<String, Object>> getJdzcUserByStudentId(Integer studentId) {
        return studentMapper.getJdzcUserByStudentId(studentId);
    }

    @Override
    public Boolean authJdzcStudent(Integer studentId) {
        List<Integer> IdList = new ArrayList<>();
        IdList.add(studentId);
        List<Map<String, Object>> schoolOrgCodeList = studentMapper.getSchoolOrgCodeListByStuIdList(IdList);
        if (schoolOrgCodeList == null || schoolOrgCodeList.size() == 0) {
            return false;
        }
        Map<String, Object> map = schoolOrgCodeList.get(0);
        //该学生的学校是否存在于该组织
        String orgCode = (String) map.get("org_code");
        if (org.apache.commons.lang.StringUtils.isBlank(orgCode)) {
            return false;
        }
        if (orgCode.startsWith(Constant.jdzcOrgCode)) {
            //校验该学生是否属于该用户
            return true;
        }
        return false;
    }

    @Override
    public List<WxUserStudentPermission> getWxUserStudentPermissionByStudentId(Integer studentId) {
        return studentMapper.getWxUserStudentPermissionByStudentId(studentId);
    }

    @Override
    public String getSchoolOrgCodeByStuId(Integer stuId) {
        return studentMapper.getSchoolOrgCodeByStuId(stuId);
    }

    @Override
    public List<Map<String, Object>> getStuByNameAndStuNo(String name, String stuNo) {
        return studentMapper.getStuByNameAndStuNo(name, stuNo);
    }

    @Override
    public List<String> getImeiListByStuIdList(List<Integer> stuIdList) {
        return studentMapper.getImeiListByStuIdList(stuIdList);
    }

    @Override
    public Map<String, Object> getStuNameAndClassNameByDeviceId(Integer deviceId) {
        return studentMapper.getStuNameAndClassNameByDeviceId(deviceId);
    }

    @Override
    public Map<String, Object> getStuNameAndClassNameByStuId(Integer stuId) {
        return studentMapper.getStuNameAndClassNameByStuId(stuId);
    }

    @Override
    public String getImeiByStuId(Integer stuId) {
        return studentMapper.getImeiByStuId(stuId);
    }

    @Override
    public Map<String, Object> getStudentByStuId(Integer stuId) {
        return studentMapper.getStudentByStuId(stuId);
    }


}
